package com.infoclue.modules.service;

import com.alibaba.fastjson.JSON;
import com.infoclue.modules.km.utils.EmbeddingUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.jeecg.modules.KM.common.utils.DictUtils;
import org.jeecg.modules.KM.entity.KmDoc;
import org.jeecg.modules.KM.service.IKmDocService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class KafkaConsumer {
    public static final String topic = "kms";

    @Autowired
    private IKmDocService kmDocService;
    @Autowired
    private EmbeddingUtil embeddingUtil;

    @KafkaListener( topics = topic, groupId = "${spring.kafka.consumer.group-id}")
    public void consume(ConsumerRecord<?, String> record) {
        log.info("------------consumerecord---------------");
        KmDoc kmdoc = JSON.parseObject(record.value(), KmDoc.class);
        log.info("------------开始上传到ES---------------"+kmdoc.getFileId()+"----getKnowledgeBase----"+kmdoc.getKnowledgeBase());
        KmDoc mykmdoc =kmDocService.indexDoc(kmdoc);
        if(kmdoc.getIskb()!=null && kmdoc.getIskb()>1) {
            mykmdoc.setKnowledgeBase(kmdoc.getKnowledgeBase());
            long iskb = 1;
            mykmdoc.setIskb(iskb);
            //mykmdoc.setPreviewFileId(kmdoc.getPreviewFileId());
            log.info("------------kmdoc.getContent()---------------" + mykmdoc.getFileId() + "--------" + mykmdoc.getPreviewFileId() + "--------" + mykmdoc.getKnowledgeBase());
            log.info("------------开始知识库向量化到MAXKB---------------" + mykmdoc.getFileId() + "--------" + mykmdoc.getKnowledgeBase());
            try {
                if (mykmdoc != null && mykmdoc.getKnowledgeBase() != null && mykmdoc.getContent() != null && !mykmdoc.getKnowledgeBase().trim().equals("") && !mykmdoc.getContent().trim().equals("")) {

                    embeddingUtil.UploadDocument(mykmdoc);
                }
            } catch (Exception ex) {
                log.error("Exception----------------" + ex.getMessage());
            }
        }
    }
}